## County level LESO control variables
library(tidyverse)
options(scipen=0, digits=7) #to standardize number of digits when exporting data. all data here is run using these options.

load('data/crime_county.RData')
load('data/econ_county.RData')
load('data/demog_county.RData')
load('data/arrest_county.RData')

## join together all controls ----------------------
controls <- inner_join(countyecon,countydemog.full,by=c("alt_county_name"="county",
                                       "state"="state",
                                       "state.fips"="state.fips",
                                       "county.fips"="county.fips",
                                       "year"="year")) %>%
  select(-state_abbrv.y) %>%
  rename(state_abbrv = state_abbrv.x, County = alt_county_name) %>%
  select(state,County,state_abbrv,state.fips,county.fips,everything())%>%
  arrange(state,County) 

# Join crime with rest of controls ------
crimecontrol <- left_join(countycrimerates,controls,by=c("State"="state_abbrv",
                                                   'County'='County',
                                                   'state.fips'='state.fips',
                                                   'county.fips'='county.fips',
                                                   'year'='year')) %>%
  rename(state_abbrv=State) %>%
  select(state_abbrv,state,County,state.fips,county.fips,year,everything()) %>%
  arrange(state,County) %>%
  group_by(County,state.fips,county.fips,state) %>% 
  complete(year = full_seq(2009:2014, 1)) %>%
  right_join(.,countyarrest,by = c("state.fips"="FIPS_ST", 
                                  "county.fips"="FIPS_CTY","year"="year"))

# save data
save(crimecontrol,file="data/county-crime-controls.RData")

